//
//  PersonnelstatisticsViewControl.m
//  YunGui
//
//  Created by User on 16/5/4.
//  Copyright © 2016年 hanen. All rights reserved.
//

#import "PersonnelstatisticsViewControl.h"
#import "UIView+Extension.h"
#import "OfficeModel.h"
#import "HYMDatePicker.h"
#import "OficeTableViewCell.h"
#import "PersonnelViewController.h"

#define Height(msg) [UIView getHeight:msg]
#define Width(msg) [UIView getWidth:msg]
#define LableHeight 20.0f
@interface PersonnelstatisticsViewControl ()<HYMDatePickerDelegate,UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
{
    NSMutableArray       *_personArray;
    
    UIScrollView  *_scrollView;
    
    UIView  *_mainView;
    CGFloat   space;
    OfficeModel *detailModel;
    NSDictionary *dataDict ;
    
    UITableView       *_tableView;
    //日历
    UIView *datePickView;
    
    UILabel *Startweek;
    UILabel *Startyear;
    UILabel *Startmonth;
    UILabel *Endweek;
    UILabel *Endyear;
    UILabel *Endmonth;
    int butttag;
    
    UIView *dateView;
    UIButton *endButton;
    
    UIView *selectedButtonView;
    
    int Page;
    NSString *currentPage;
    NSString *currentNum;
    
    NSString *searchStartDate;
    NSString *searchEndDate;
    
    //判断日历是否 滑动
    BOOL IsScrolled;
    
    int endtType;
    int time;
    int YearCount;
    int count;
    
}

@property (nonatomic, strong) NSString *month;
@property (nonatomic, strong) NSString *year;
@property (nonatomic, strong) NSDate   *date;
@end

@implementation PersonnelstatisticsViewControl
- (void)viewWillDisappear:(BOOL)animated
{
    time = 0;
    count = 0;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    YearCount = CHOOSE_YEAR_COUNT;
    
    _personArray = [[NSMutableArray alloc] init];
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.navigationItem.leftBarButtonItem=[ViewTool getBackBarButtonItemWithTarget:self WithAction:@selector(goToBack)];
    space = [UIView getHeight:10.0f];
    [ViewTool setNavigationBar:self.navigationController.navigationBar];
    self.navigationItem.title = self.Title;
    
    [self createCalendar];
    [self addTableview];
}

- (void)createCalendar
{
    [self creatdatePickView];

    dateView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 155)];
    dateView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:dateView];
    
    UIButton *DatePickButt = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth/2.0-Width(40), 5, Width(80), 30)];
    [DatePickButt setTitle:@"日期选择" forState:UIControlStateNormal];
    [DatePickButt setTitleColor:GRAYCOLOR forState:UIControlStateNormal];
    DatePickButt.titleLabel.textAlignment = NSTextAlignmentCenter;
    [dateView addSubview:DatePickButt];
    
    //获取当天所在的 年 月 日 星期
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    NSDateFormatter *inputFormatter= [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh"]];
    inputFormatter.dateFormat = @"EE";
    
    NSString * week = [inputFormatter stringFromDate: [NSDate date]];
    NSString *day = [NSString stringWithFormat:@"%d",(int)[dateComponent day]];
    if ([day intValue] < 10) {
        day = [NSString stringWithFormat:@"0%d",(int)[dateComponent day]];
    }
    
    NSString *month = [NSString stringWithFormat:@"%d",(int)[dateComponent month]];
    if ([month intValue] < 10) {
        month = [NSString stringWithFormat:@"0%d",(int)[dateComponent month]];
    }
    NSString *year = [NSString stringWithFormat:@"%d",(int)[dateComponent year]];
    
    Startweek = [ViewTool getLabelWith:CGRectMake(DatePickButt.x - Width(65), DatePickButt.maxY+3, Width(30), 30) WithTitle:week WithFontSize:14 WithTitleColor:GRAYCOLOR WithTextAlignment:NSTextAlignmentLeft];
    Startmonth = [ViewTool getLabelWith:CGRectMake(Startweek.x, Startweek.maxY, Width(100), 30) WithTitle:[NSString stringWithFormat:@"%@.%@",month,day] WithFontSize:26 WithTitleColor:UIColorFromRGB(0xff7701) WithTextAlignment:NSTextAlignmentLeft];
    Startyear = [ViewTool getLabelWith:CGRectMake(Startweek.x+10, Startmonth.maxY, Width(80), 30) WithTitle:year WithFontSize:14 WithTitleColor:BLACKCOLOR WithTextAlignment:NSTextAlignmentLeft];
    
    UIImageView *dateImage = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth/2.0-12, Startmonth.y, 24, 24)];
    dateImage.image = [UIImage imageNamed:@"Btn_Normal_Riqi"];
    [dateView addSubview:dateImage];
    
    Endweek = [ViewTool getLabelWith:CGRectMake(DatePickButt.maxX + Width(10), DatePickButt.maxY+3, Width(30), 30) WithTitle:week WithFontSize:14 WithTitleColor:GRAYCOLOR WithTextAlignment:NSTextAlignmentLeft];
    Endmonth = [ViewTool getLabelWith:CGRectMake(Endweek.x, Endweek.maxY, Width(100), 30) WithTitle:[NSString stringWithFormat:@"%@.%@",month,day] WithFontSize:26 WithTitleColor:UIColorFromRGB(0xff7701) WithTextAlignment:NSTextAlignmentLeft];
    Endyear = [ViewTool getLabelWith:CGRectMake(Endweek.x+10, Endmonth.maxY, Width(80), 30) WithTitle:year WithFontSize:14 WithTitleColor:BLACKCOLOR WithTextAlignment:NSTextAlignmentLeft];
    searchStartDate = [NSString stringWithFormat:@"%@-%@-%@",year,month,day];
    searchEndDate = [NSString stringWithFormat:@"%@-%@-%@",year,month,day];
    
    WeekString = week;
    dayString = day;
    monthString = month;
    yearString = year;
    
    [dateView addSubview:Startweek];
    [dateView addSubview:Startmonth];
    [dateView addSubview:Startyear];
    
    [dateView addSubview:Endweek];
    [dateView addSubview:Endmonth];
    [dateView addSubview:Endyear];
    
    UIButton *startButt = [[UIButton alloc] initWithFrame:CGRectMake(Startweek.x, Startweek.y, Width(50), 90)];
    startButt.tag = 0;
    [startButt addTarget:self action:@selector(DatepickViewShow:) forControlEvents:UIControlEventTouchUpInside];
    [dateView addSubview:startButt];
    
    UIButton *endButt = [[UIButton alloc] initWithFrame:CGRectMake(Endweek.x, Startweek.y, Width(50), 90)];
    endButt.tag = 1;
    [endButt addTarget:self action:@selector(DatepickViewShow:) forControlEvents:UIControlEventTouchUpInside];
    [dateView addSubview:endButt];
    [self CreatLine:self.view Y:140];

}
- (void)creatdatePickView
{
    datePickView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    
    [self.view addSubview:datePickView];
    UIView *BGview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-220-64)];
    BGview.backgroundColor = [UIColor blackColor];
    BGview.alpha = 0.6;
    [datePickView addSubview:BGview];
    
    UIView *DownBgview = [[UIView alloc] initWithFrame:CGRectMake(0, BGview.maxY, kScreenWidth, 220)];
    DownBgview.backgroundColor = [UIColor whiteColor];
    [datePickView addSubview:DownBgview];
    
    UIButton *yesButton = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth - 70, 0, 60, 40)];
    [yesButton setTitle:@"确定" forState:UIControlStateNormal];
    [yesButton setTitleColor:BLACKCOLOR forState:UIControlStateNormal];
    yesButton.tag = 0;
    yesButton.titleLabel.font = [ViewTool getFont:15.0f];
    [yesButton addTarget:self action:@selector(ButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [DownBgview addSubview:yesButton];
    
    UIButton *noButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 0, 60, 40)];
    [noButton setTitle:@"取消" forState:UIControlStateNormal];
    [noButton setTitleColor:GRAYCOLOR forState:UIControlStateNormal];
    noButton.tag = 1;
    noButton.titleLabel.font = [ViewTool getFont:15.0f];
    [noButton addTarget:self action:@selector(ButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [DownBgview addSubview:noButton];
    
    UILabel *upXian = [[UILabel alloc] initWithFrame:CGRectMake(0, noButton.maxY, kScreenWidth, 1)];
    upXian.backgroundColor = GRAYLINECOLOR;
    [DownBgview addSubview:upXian];
    
    HYMDatePicker *datePick = [[HYMDatePicker alloc] init];
    datePick.frame = CGRectMake(0, upXian.maxY , kScreenWidth, DownBgview.height-70);
    datePick.delegateDiy = self;
    [datePick selectRow:YearCount inComponent:0 animated:NO];
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSDayCalendarUnit|NSMonthCalendarUnit;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    int day = (int)[dateComponent day];
    int month = (int)[dateComponent month];
    
    [datePick selectRow:YearCount-1 inComponent:0 animated:NO];
    [datePick selectRow:month-1 inComponent:1 animated:NO];
    [datePick selectRow:day-1 inComponent:2 animated:NO];
    
    [DownBgview addSubview:datePick];
}
- (void)ButtonClick:(UIButton *)butt
{
    if (IsScrolled == NO) {
        if (butt.tag == 1) {
            [self.view sendSubviewToBack:datePickView];
            return;
        }else{
            if (butttag == 0) {
                [self datepickstart];
                
            }else if (butttag == 1){
                [self datepickend];
            }
            count ++;
            [_tableView.mj_header beginRefreshing];
            [_personArray removeAllObjects];
            [self loadNewData];
        }
    }else{

    if (butt.tag == 0) {
        if (butttag == 0) {
            NSArray *endArr = [Endmonth.text componentsSeparatedByString:@"."];
            int endM = [[endArr objectAtIndex:0] intValue];
            int endD = [[endArr objectAtIndex:1] intValue];
            
            if ([yearString intValue] > [Endyear.text intValue]) {
                [Tools showMessage:@"起始日期不能大于结束日期" view:self];
                return;
            }
            if ([yearString intValue] == [Endyear.text intValue]){
                if ([monthString intValue] > endM) {
                    [Tools showMessage:@"起始日期不能大于结束日期" view:self];
                    return;
                }
                if ([monthString intValue] == endM){
                    if ([dayString intValue] > endD) {
                        [Tools showMessage:@"起始日期不能大于结束日期" view:self];
                        return;
                    }
                }
            }
            [self datepickstart];
        }
        else{
            NSArray *startArr = [Startmonth.text componentsSeparatedByString:@"."];
            int startM = [[startArr objectAtIndex:0] intValue];
            int startD = [[startArr objectAtIndex:1] intValue];
            
            if ([yearString intValue] < [Startyear.text intValue]) {
                [Tools showMessage:@"结束日期不能小于起始日期" view:self];
                return;
            }
            if ([yearString intValue] == [Startyear.text intValue]){
                if ([monthString intValue] < startM) {
                    [Tools showMessage:@"结束日期不能小于起始日期" view:self];
                    return;
                }
                if ([monthString intValue] == startM){
                    if ([dayString intValue] < startD) {
                        [Tools showMessage:@"结束日期不能小于起始日期" view:self];
                        return;
                    }
                }
            }
            [self datepickend];
        }

        count ++;
        [_tableView.mj_header beginRefreshing];
        [_personArray removeAllObjects];
        [self loadNewData];
        IsScrolled = NO;
    }
    else if (butt.tag == 1)
    {
        [self.view sendSubviewToBack:datePickView];
    }
    }
}
- (void)datepickstart
{
    Startweek.text = WeekString;
    Startmonth.text = [NSString stringWithFormat:@"%@.%@",monthString,dayString];
    Startyear.text = yearString;
    searchStartDate = [NSString stringWithFormat:@"%@-%@-%@",yearString,monthString,dayString];
    [self.view sendSubviewToBack:datePickView];
}
- (void)datepickend
{
    Endweek.text = WeekString;
    Endmonth.text = [NSString stringWithFormat:@"%@.%@",monthString,dayString];
    Endyear.text = yearString;
    searchEndDate = [NSString stringWithFormat:@"%@-%@-%@",yearString,monthString,dayString];
    [self.view sendSubviewToBack:datePickView];
}

- (void)currentSelectedDate:(NSString *)yearStr month:(NSString *)monthStr day:(NSString *)dayStr{
    
    IsScrolled = YES;
    
    NSString *dateStr = [NSString stringWithFormat:@"%@%@%@",yearStr,monthStr,dayStr];
    
    NSDateFormatter *inputFormatter= [[NSDateFormatter alloc] init];
    
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh"]];
    
    [inputFormatter setDateFormat:@"yyyyMMdd"];
    
    NSDate*inputDate = [inputFormatter dateFromString:dateStr];
    
    inputFormatter.dateFormat = @"EE";
    NSString * weekString = [inputFormatter stringFromDate: inputDate];
    yearString = yearStr;
    monthString = monthStr;
    dayString = dayStr;
    WeekString = weekString;
}

- (void)DatepickViewShow:(UIButton *)butt
{
    butttag = (int)butt.tag;
    [self.view bringSubviewToFront:datePickView];
}

//自定义的leftBarButton
- (UIBarButtonItem *)changeBarButtonWithImageName:(NSString *)imageName
{
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    [btn setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    return barItem;
}

- (void)CreatLine:(UIView *)view Y:(float)y
{
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, y, self.view.width, 15.0f)];
    backView.backgroundColor = UIColorFromRGB(0xf8f8fa);
    
    UIView *line1 = [ViewTool getLineViewWith:CGRectMake(0, 0, kScreenWidth, 1) withBackgroudColor:UIColorFromRGB(0xe6e7eb)];
    [backView addSubview:line1];
    
    UIView *line2 = [ViewTool getLineViewWith:CGRectMake(0, 14, kScreenWidth, 1) withBackgroudColor:UIColorFromRGB(0xe6e7eb)];
    [backView addSubview:line2];
    [view addSubview:backView];
}

- (void)loadNewData
{
    [self initDetailData];
}

#pragma mark --tableview
- (void)addTableview
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 155, kScreenWidth, kScreenHeight-155-64) style:UITableViewStylePlain];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = GrayBackColor;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self loadNewData];
    }];
    [_tableView.mj_header beginRefreshing];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _personArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OficeTableViewCell *cell = [OficeTableViewCell cellWithTableView:tableView];
    cell.officelabel.text = @"人员名称:";
    if (_personArray.count != 0) {
        [cell setModel:_personArray[indexPath.row]];
        cell.NumberLabel.text = [NSString stringWithFormat:@"%d",(int)indexPath.row+1];
    }
    
    return cell;

}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    PersonnelViewController *vc = [[PersonnelViewController alloc] init];
    OfficeModel *model = _personArray[indexPath.row];
    
    vc.Title =model.realname;
    vc.districtID = model.user_id;
    [self.navigationController pushViewController:vc animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [OficeTableViewCell cellHeight];
   
}
- (void)initDetailData
{
    NSString *timearea = [NSString stringWithFormat:@"2005-09-02,%@",searchEndDate];
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:@{@"method":@"app.visit.count.agency",@"agency_id":self.districtID,@"timearea":timearea}];
    if (count != 0) {
        timearea = [NSString stringWithFormat:@"%@,%@",searchStartDate,searchEndDate];
        [dict setObject:timearea forKey:@"timearea"];
    }
    NSDictionary *paramesDict = [DataTool addSignToDic:dict];
    [_personArray removeAllObjects];
    [DataTool postWithUrl:HEAD_URL parameters:paramesDict success:^(id data) {
        id backData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments | NSJSONReadingMutableContainers error:nil];
        NSString *status = [(NSDictionary *)backData objectForKey:@"status"];
        
        if ([status isEqualToString:@"SUCCESS"]) {
            dataDict = backData[@"data"];
            NSArray *info = [backData objectForKey:@"data"];
            for (NSDictionary *dic in info) {
                detailModel = [[OfficeModel alloc] init];
                [detailModel setValuesForKeysWithDictionary:dic];
                [_personArray addObject:detailModel];
            }
            [_tableView reloadData];
            [_tableView.mj_header endRefreshing];
        } else {
            NSString *msg = [(NSDictionary *)backData objectForKey:@"msg"];
            [SVProgressHUD showErrorWithStatus:msg];
            [_tableView.mj_header endRefreshing];
        }
    } fail:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        NSLog(@"%@",error.localizedDescription);
        [_tableView.mj_header endRefreshing];
    }];
}

- (void)goToBack{
    
    [self.navigationController popViewControllerAnimated:YES];
}

@end
